package cn.walls1717.juc.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * FutureTask获取结果的几种方式
 *
 * @author walls1717
 * @create 2022/12/08 23:11
 **/
@Slf4j
public class FutureApiDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(() -> {
            log.info("futureTask come in ...");
            TimeUnit.SECONDS.sleep(5);
            return "futureTask";
        });
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();
        log.info(Thread.currentThread().getName() + "线程执行任务");

        // log.info("futureTask result is {}", futureTask.get());
        // 等待3s，超过3s后直接抛出超时异常，不会一直阻塞等待。
        // log.info("futureTask result is {}", futureTask.get(3, TimeUnit.SECONDS));

        // 使用轮询来控制长业务的处理，但是可能造成cpu空转。
        while (true) {
            // isDone()可以判断业务是否执行完成
            if (futureTask.isDone()) {
                log.info("futureTask result is {}", futureTask.get());
                break;
            } else {
                TimeUnit.SECONDS.sleep(1);
                log.info("正在处理中...");
            }
        }
    }
}
